﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class GameClient : UniBrickClient
{
    private readonly Dictionary<string, Transform> _networkPlayers;
    public readonly Transform MinifigModel;

    public string Username;

    public GameClient(Transform minfigModel)
    {
        _networkPlayers = new Dictionary<string, Transform>();
        MinifigModel = minfigModel;
    }

    public override void CreatePlayer(string playerName)
    {
        var newPlayer = Object.Instantiate(MinifigModel);
        _networkPlayers.Add(playerName, newPlayer);
        Debug.Log("Added player " + playerName);
    }

    public override void RemovePlayer(string playerName)
    {
        Object.Destroy(_networkPlayers[playerName].gameObject);
        _networkPlayers.Remove(playerName);
        Debug.Log("Removed player " + playerName);
    }

    public override void UpdatePlayer(string playerName, Vector3 position, Quaternion rotation)
    {
        if (_networkPlayers.ContainsKey(playerName))
        {
            Debug.Log("Old pos: " + _networkPlayers[playerName].position);
            Debug.Log("Old rot:" + _networkPlayers[playerName].rotation);
            _networkPlayers[playerName].position = position;
            _networkPlayers[playerName].rotation = rotation;
            Debug.Log("New pos: " + _networkPlayers[playerName].position);
            Debug.Log("New rot: " + _networkPlayers[playerName].rotation);
        }
    }

    public override void UpdatePlayers(List<string> playerList)
    {
        if (!Connection.Instance.GameStarted) return;

        foreach (var playerName in playerList.Where(playerName => !_networkPlayers.ContainsKey(playerName)).Where(playerName => playerName != Username))
        {
            CreatePlayer(playerName);
        }

        foreach (var playerName in _networkPlayers.Keys.Where(playerName => !playerList.Contains(playerName)).Where(playerName => playerName != Username))
        {
            RemovePlayer(playerName);
        }
    }
}